/**  定义文章相关的接口 */
const express = require("express");
const router = express.Router();
const Joi = require("joi");
const Response = require("../utils/Response.js");

// 引入mysql连接池
const pool = require("../utils/db.js");



router.post("/essay/add", (req, resp) => {
  let {
    essay_id,
    essay_title,
    essay_description,
    longitude,
    essay_pic,
    latitude
  } = req.body; // post请求参数在req.body中

  // 表单验证
  let schema = Joi.object({
    essay_id: Joi.string().required(),
    essay_title: Joi.string().required(),
    essay_description: Joi.string().required(),
    essay_pic: Joi.string().required(),
    longitude: Joi.number().required(),
    latitude: Joi.number().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }

  // 表单验证通过，执行添加操作
  let sql = `insert into user_essay (
    essay_id,
    essay_title,
    essay_description,
    longitude,
    essay_pic,
    latitude,
     ) values (?,?,?,?,?,?)`;
  pool.query(
    sql,
    [essay_id,
      essay_title,
      essay_description,
      longitude,
      essay_pic,
      latitude],
    (error, result) => {
      if (error) {
        resp.send(Response.error(500, error));
        throw error;
      }
      resp.send(Response.ok());
    }
  );
});
/**
 * 删除文章接口
 * @param:
 *   id:   文章essay_id
 * @return:
 *   {code:200, msg:'ok'}
 */
router.post("/essay/del", (req, resp) => {

  // 执行删除业务
  let sql = "delete from user_essay where essay_id = ?";
  pool.query(sql, [essay_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  });
});


/**
 * 查询当前游记中所有的文章
 * @param:
 *   essay_id:  文章essay_id
 * @return:
 *   {code:200, msg:'ok', data:[{}]}
 */
router.get("/essay/essay_id", (req, resp) => {
  let { essay_id } = req.query;
  // 表单验证
  let schema = Joi.object({
    essay_id: Joi.string().required(), // 必填
  });
  let { error, value } = schema.valessay_idate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }

  // 执行查询操作
  let sql = "select * from user_essay where essay_id=?";
  pool.query(sql, [essay_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok(result));
  });
});
// 将router对象导出
module.exports = router;
